{% extends "base.html" %}

{% block title %}人脸录入{% endblock %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-md-8">
        <h2 class="text-center mt-3">人脸录入</h2>
        
        <div class="card mt-4">
            <div class="card-body">
                <h5 class="card-title">操作说明</h5>
                <ul class="list-group list-group-flush">
                    <li class="list-group-item">1. 点击"开始摄像头"按钮启动摄像头</li>
                    <li class="list-group-item">2. 确保面部在画面中且清晰可见</li>
                    <li class="list-group-item">3. 点击"采集样本"按钮保存当前人脸数据</li>
                    <li class="list-group-item">4. 建议采集5-10个不同角度的人脸样本</li>
                </ul>
            </div>
        </div>
        
        <div class="video-container mt-4">
            <video id="video" class="video-feed" autoplay playsinline></video>
        </div>
        
        <div class="controls">
            <button id="startCamera" class="btn btn-primary">开始摄像头</button>
            <button id="capture" class="btn btn-success" disabled>采集样本</button>
            <button id="stopCamera" class="btn btn-secondary" disabled>停止摄像头</button>
        </div>
        
        <div id="status" class="status text-center"></div>
        <div id="sampleCount" class="text-center mt-2"></div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    let video = document.getElementById('video');
    let startCameraBtn = document.getElementById('startCamera');
    let captureBtn = document.getElementById('capture');
    let stopCameraBtn = document.getElementById('stopCamera');
    let statusDiv = document.getElementById('status');
    let sampleCountDiv = document.getElementById('sampleCount');
    let stream = null;
    
    // 获取已采集样本数量
    function updateSampleCount() {
        fetch('/api/get_samples_count')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    sampleCountDiv.innerHTML = `已采集样本数: ${data.count}`;
                }
            });
    }
    
    // 启动摄像头
    startCameraBtn.addEventListener('click', async () => {
        try {
            stream = await navigator.mediaDevices.getUserMedia({ video: true });
            video.srcObject = stream;
            startCameraBtn.disabled = true;
            captureBtn.disabled = false;
            stopCameraBtn.disabled = false;
            statusDiv.innerHTML = '<span class="text-success">摄像头已启动</span>';
            updateSampleCount();
        } catch (err) {
            statusDiv.innerHTML = '<span class="text-danger">无法访问摄像头: ' + err.message + '</span>';
        }
    });
    
    // 停止摄像头
    stopCameraBtn.addEventListener('click', () => {
        if (stream) {
            const tracks = stream.getTracks();
            tracks.forEach(track => track.stop());
            video.srcObject = null;
            stream = null;
        }
        startCameraBtn.disabled = false;
        captureBtn.disabled = true;
        stopCameraBtn.disabled = true;
        statusDiv.innerHTML = '<span class="text-info">摄像头已停止</span>';
    });
    
    // 采集样本
    captureBtn.addEventListener('click', () => {
        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        
        // 转换为base64格式
        const imageData = canvas.toDataURL('image/jpeg');
        
        // 发送到服务器
        fetch('/api/train', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ image: imageData })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                statusDiv.innerHTML = `<span class="text-success">${data.message}</span>`;
                updateSampleCount();
            } else {
                statusDiv.innerHTML = `<span class="text-danger">${data.message}</span>`;
            }
        })
        .catch(error => {
            statusDiv.innerHTML = `<span class="text-danger">采集失败: ${error.message}</span>`;
        });
    });
    
    // 页面加载时更新样本数量
    updateSampleCount();
</script>
{% endblock %}